// src/middleware/logger.middleware.ts
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response } from 'express';

import { LoggerService } from '../modules/Logger/logger.service';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  constructor(private logger: LoggerService) {}

  use(req: Request, res: Response, next: () => void) {
    const code = res.statusCode; // 响应状态码

    // 组装日志信息
    const logFormat = `\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        Request original url: ${req.originalUrl}
        Method: ${req.method}
        IP: ${req.ip}
        Status code: ${code}
        Parmas: ${JSON.stringify(req.params)}
        Query: ${JSON.stringify(req.query)}
        Body: ${JSON.stringify(
          req.body,
        )} \n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    `;

    // 根据状态码，进行日志类型区分
    if (code >= 500) {
      this.logger.error(logFormat, 'API Request');
    } else if (code >= 400) {
      this.logger.warn(logFormat, 'API Request');
    } else {
      this.logger.log(logFormat, 'API Request');
    }
    this.logger.access(logFormat);

    next();
  }
}
